import { prepareExecute } from '.'

/**
 * 数据库 blog 表
 */
// export class BlogModel {
//   id?: number
//   title?: string
//   description?: string
//   cover?: string
//   content?: string
//   tag?: string
//   createTime?: string
//   updateTime?: string
// }

export const addBlogDao = async (blogInfo) => {
  const sql = `insert into blog values(NULL, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`
  const values = [
    blogInfo['title'],
    blogInfo['remark'],
    blogInfo['cover'],
    blogInfo['content'],
    blogInfo['type'],
    blogInfo['tag'],
  ]
  return await prepareExecute(sql, values)
}

export const queryBlogByIdDao = async (id) => {
  const sql = 'select * from blog where id = ?'
  const values = [id]
  return await prepareExecute(sql, values)
}

export const queryBlogsByConditonDao = async (condition) => {
  const { keywords, page, pageSize } = condition
  const whereCondition = keywords.trim() ? `title like '%${keywords}%' or \`remark\` like '%${keywords}%' or content like '%${keywords}%'` : '1=1'
  const start = Number(pageSize) * (Number(page) - 1)
  const sql = `select id, title, remark, cover, tag, type, update_time from blog where ${whereCondition} limit ${start}, ${Number(pageSize)}`
  const total = await prepareExecute('select count(*) as total from blog', [])
  const list = await prepareExecute(sql, [])
  return {
    page: Number(page), 
    pageSize: Number(pageSize), 
    total: total[0].total, 
    list,
  }
}

export const updateBlogDao = async (id, blogInfo) => {
  const blogEntry = Object.entries(blogInfo)
  const lastIndex = blogEntry.length - 1
  if (lastIndex < 0) return // 如果为 {} 则什么也不做
  const setValue = []
  const setSql = blogEntry.reduce((sql, [key, value], index) => {
    setValue.push(value)
    let subStr = `${key} = ?`
    if (index !== lastIndex) subStr += ','
    return sql + subStr
  }, 'set ')
  const sql = `update blog ${setSql} where id = ?`
  const values = [...setValue, id]
  return await prepareExecute(sql, values)
}

export const deleteBlogDao = async (id) => {
  const sql = 'delete from blog where id = ?'
  return await prepareExecute(sql, [id])
}